package ldh.im.client.util;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ldh123 on 2018/10/13.
 */
public class RsaUtil {

    //非对称密钥算法
    public static final String KEY_ALGORITHM = "RSA";

    /**
     * 密钥长度，DH算法的默认密钥长度是1024
     * 密钥长度必须是64的倍数，在512到65536位之间
     */
    private static final int KEY_SIZE = 1024;
    //公钥
    private static final String PUBLIC_KEY = "RSAPublicKey";

    //私钥
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * 初始化密钥对
     *
     * @return Map 甲方密钥的Map
     */
    public static Map<String, Object> initKey() throws Exception {
        //实例化密钥生成器
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        //初始化密钥生成器
        keyPairGenerator.initialize(KEY_SIZE);
        //生成密钥对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        //甲方公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        //甲方私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        //将密钥存储在map中
        Map<String, Object> keyMap = new HashMap<String, Object>();
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;

    }

    /**
     * 私钥加密
     *
     * @param data 待加密数据
     * @param key       密钥
     * @return byte[] 加密数据
     */
    public static String encryptByPrivateKey(String data, String key) throws Exception {
        //取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        //生成私钥
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        //数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] bytes = cipher.doFinal(data.getBytes("utf-8"));
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * 公钥加密
     *
     * @param data 待加密数据
     * @param key       密钥
     * @return byte[] 加密数据
     */
    public static String encryptByPublicKey(String data, String key) throws Exception {

        //实例化密钥工厂
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        //初始化公钥
        //密钥材料转换
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
        //产生公钥
        PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);

        //数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] bytes = cipher.doFinal(data.getBytes("utf-8"));
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * 私钥解密
     *
     * @param data 待解密数据
     * @param key  密钥
     * @return byte[] 解密数据
     */
    public static String decryptByPrivateKey(String data, String key) throws Exception {
        //取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        //生成私钥
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        //数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(data));
        return new String(bytes, "utf-8");
    }

    /**
     * 公钥解密
     *
     * @param data 待解密数据
     * @param key  密钥
     * @return byte[] 解密数据
     */
    public static String decryptByPublicKey(String data, String key) throws Exception {

        //实例化密钥工厂
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        //初始化公钥
        //密钥材料转换
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
        //产生公钥
        PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
        //数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, pubKey);
        byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(data));
        return new String(bytes, "utf-8");
    }

    /**
     * 取得私钥
     *
     * @param keyMap 密钥map
     * @return byte[] 私钥
     */
    public static String getPrivateKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        byte[] bytes = key.getEncoded();
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * 取得公钥
     *
     * @param keyMap 密钥map
     * @return byte[] 公钥
     */
    public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        byte[] bytes = key.getEncoded();
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        //初始化密钥
        //生成密钥对
        Map<String, Object> keyMap = RsaUtil.initKey();

//        String publicKey = RsaUtil.getPublicKey(keyMap);
//        String privateKey = RsaUtil.getPrivateKey(keyMap);

        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCyIyjvfv2qF8Q/2+at8Iy67PnQ56oZVUMrssZL2w+CXzPgC00UD8aZFx2LBXU+tT0mRO/hWcxf8HE2Yb2IXko9zGAjmSYIWQ54c7x8XkFbHaeg3hwvY+nMa5LRt1I/xLA+dKAGGojFvwCXefaLQVi+/TQ6OyTUN0LsJbeF/jb+0QIDAQAB";
        String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALIjKO9+/aoXxD/b5q3wjLrs+dDnqhlVQyuyxkvbD4JfM+ALTRQPxpkXHYsFdT61PSZE7+FZzF/wcTZhvYheSj3MYCOZJghZDnhzvHxeQVsdp6DeHC9j6cxrktG3Uj/EsD50oAYaiMW/AJd59otBWL79NDo7JNQ3Quwlt4X+Nv7RAgMBAAECgYAK++IFSnZHq6l9KokBxqhWyk/pEq/JWhmHM0HI4ZwGNOqU8P1ytDpRrDw1G0QMds5rcqq74XaZn9DLQqGWLAI1zPNq8daF/hMOcckhCFwhtoFpgh5Qblr4d2TnAlL7GMkP9n7C9+GD+N953C347msr9d6wbCOBD/QmkVv5KFpa8QJBANaNUOM9rkDGYDa++NaeXi7bh/xWGuCK2iLxmZEiSe+l0EnVbn7Q9ceoe6WMCaKg3R47ZHCTNF9wY/K357bNkB0CQQDUjPQ09ZpbnsnyY+ZjpKFqAaCsEErTW3kyj3Sie2Jd3jo/ZdXXXRqBW1tD/LZt/r9n1OWTlcr0smFVPKfTARNFAkBtJZ8Mu4g2M7UmpKh6pj5LoCrh1/v8Vyb5t+bjyonKfJQlu4pmwW8Hj1K3uTH9pdBXXOePzZNLKiXuiFg8yv6RAkEAgoUb4PmAlApqEEJwU3fg9uuQ8pf+mtNtFTMqeCw0N1gjhJLQQbOWdyDWZmVk0R7CAsylPX+aZbC0PFdG5zed0QJBALUSmoKbHH9P3rW/Hd1pYfSmhuXMIktWE1hdY0xbkSViIBTfOJib+iHDKugfVUGP+zr0zgpyFY/XP7onHTCiAXA=";


        System.out.println("公钥：" + publicKey);
        System.out.println("私钥：" + privateKey);

        System.out.println("================密钥对构造完毕,甲方将公钥公布给乙方，开始进行加密数据的传输=============");
        String str = "RSA密码交换算法";
        System.out.println("/n===========甲方向乙方发送加密数据==============");
        System.out.println("原文:" + str);
        //甲方进行数据的加密
        String code1 = RsaUtil.encryptByPrivateKey(str, privateKey);
        System.out.println("加密后的数据：" + code1);
        System.out.println("===========乙方使用甲方提供的公钥对数据进行解密==============");
        //乙方进行数据的解密
        String decode1 = RsaUtil.decryptByPublicKey(code1, publicKey);
        System.out.println("乙方解密后的数据：" + decode1 + "/n/n");

        System.out.println("===========反向进行操作，乙方向甲方发送数据==============/n/n");

        str = "乙方向甲方发送数据RSA算法";

        System.out.println("原文:" + str);

        //乙方使用公钥对数据进行加密
        String code2 = RsaUtil.encryptByPublicKey(str, publicKey);
        System.out.println("===========乙方使用公钥对数据进行加密==============");
        System.out.println("加密后的数据：" + code2);

        System.out.println("=============乙方将数据传送给甲方======================");
        System.out.println("===========甲方使用私钥对数据进行解密==============");

        //甲方使用私钥对数据进行解密
        String decode2 = RsaUtil.decryptByPrivateKey(code2, privateKey);

        System.out.println("甲方解密后的数据：" + decode2);
    }
}
